package poli.tidia.mobile.proxy;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import poli.tidia.mobile.model.Forum;
import poli.tidia.mobile.model.ForumThread;
import poli.tidia.mobile.model.Message;
import poli.tidia.mobile.model.Site;
import poli.tidia.mobile.model.Topic;
import poli.tidia.mobile.proxy.RestClient.RequestMethod;

public class ForunsProxy {
	public List<Forum> getForums(Site site)
	{
		List<Forum> result = new ArrayList<Forum>();
		
		try {
        	Document doc;
        	String response;
        	RestClient client;
        	if(site.getDiscussionBoardPortletUrl().equals(""))
        	{
	        	client = RestClient.getInstance(site.getDiscussionBoardUrl());
	            client.Execute(RestClient.RequestMethod.GET);
				response = client.getResponse();
		        doc = Jsoup.parse(response);
		        String portletUrl = doc.select(".portletMainWrap").first().child(0).attr("src");
		        portletUrl = portletUrl.substring(0, portletUrl.lastIndexOf("?"));
		        site.setDiscussionBoardPortletUrl(portletUrl);
        	}
        	
        	client = RestClient.getInstance(site.getDiscussionBoardPortletUrl());
        	client.Execute(RestClient.RequestMethod.GET);
        	response = client.getResponse();
        	doc = Jsoup.parse(response);
        	
        	Elements discussionsDOM = doc.select("table[id=msgForum:forums] > tbody > tr");
        	for (int i = 0; i < discussionsDOM.size(); i++) {
    			Element forumElement = discussionsDOM.get(i);
    			Element forumTitle = forumElement.select("table[class=hierItemBlock specialLink] h4 > a").first();
    			
    			String name = forumTitle.text();
    			String forumId = forumTitle.attr("onclick");
    			forumId = forumId.substring(forumId.indexOf("['forumId'].value='") + 19);
    			forumId = forumId.substring(0, forumId.indexOf("'"));
    			int id = Integer.parseInt(forumId);
    			
    			Forum forum = new Forum(id, name);
    			Elements topicsDOM = forumElement.select("table.topicBloc > tbody > tr");
    			for (int j = 0; j < topicsDOM.size(); j++) {
					Element topicElement = topicsDOM.get(j);
    				Element topicTitle = topicElement.select("table.specialLink h5 > a").first();
    				
    				
    				String strTopicId = topicTitle.attr("onclick");
    				strTopicId = strTopicId.substring(strTopicId.indexOf("['topicId'].value='") + 19);
    				strTopicId = strTopicId.substring(0, strTopicId.indexOf("'"));
    				int topicId = Integer.parseInt(strTopicId);
    				String topicName = topicTitle.text();
    				String internalId = topicTitle.id();
    				
    				forum.getTopics().add(new Topic(topicId, internalId, topicName, forum));
				}
    			result.add(forum);
        	}
        } catch (Exception e) {
            e.printStackTrace();
        }
		
		return result;
	}
	
	public List<ForumThread> getTopicThreads(Site site, Topic topic)
	{
		List<ForumThread> result = new ArrayList<ForumThread>();
		
		try {
        	Document doc;
        	String response;
        	RestClient client;
        	if(site.getDiscussionBoardPortletUrl().equals(""))
        	{
	        	client = RestClient.getInstance(site.getDiscussionBoardUrl());
	            client.Execute(RestClient.RequestMethod.GET);
				response = client.getResponse();
		        doc = Jsoup.parse(response);
		        String portletUrl = doc.select(".portletMainWrap").first().child(0).attr("src");
		        portletUrl = portletUrl.substring(0, portletUrl.lastIndexOf("?"));
		        site.setDiscussionBoardPortletUrl(portletUrl);
        	}
        	
        	client = RestClient.getInstance(site.getDiscussionBoardPortletUrl() + "/discussionForum/forumsOnly/dfForums");
    		
        	client.AddParam("msgForum", "msgForum");
        	client.AddParam("msgForum:_idcl", topic.getInternalId());
        	client.AddParam("topicId", String.valueOf(topic.getId()));
        	client.AddParam("forumId", String.valueOf(topic.getParent().getId()));
        	
        	client.Execute(RestClient.RequestMethod.POST);
        	response = client.getResponse();
        	doc = Jsoup.parse(response);
        	
        	Elements threadsDOM = doc.select("table[id=msgForum:messagesInHierDataTable] > tbody > tr.hierItemBlock");
        	for (int i = 0; i < threadsDOM.size(); i++) {
        		Elements threadElements = threadsDOM.get(i).select("td");
        		Element threadTitleElement = threadElements.get(1).select("a:gt(0)").first();
        		
        		String tmpParse = threadTitleElement.attr("onclick");
        		tmpParse = tmpParse.substring(tmpParse.indexOf("['messageId'].value='") + 21);
        		tmpParse = tmpParse.substring(0, tmpParse.indexOf("'"));
        		int threadId = Integer.parseInt(tmpParse);
        		
        		tmpParse = threadTitleElement.attr("onclick");
        		tmpParse = tmpParse.substring(tmpParse.indexOf("['msgForum:_idcl'].value='") + 26);
        		tmpParse = tmpParse.substring(0, tmpParse.indexOf("'"));
        		String internalId = tmpParse;
        		
        		String name = threadTitleElement.text();
        		
        		String author = threadElements.get(2).text();
        		
        		String strDate = threadElements.get(3).text();
				SimpleDateFormat curFormater = new SimpleDateFormat("MMM, dd, yyyy h:mm a"); 
	        	Date modifiedDate = curFormater.parse(strDate); 
	        	
	        	result.add(new ForumThread(threadId, internalId, name, author, modifiedDate, topic));
        	}
		} catch (Exception e) {
            e.printStackTrace();
        }
		
		return result;
	}
	
	public List<Message> getThreadMessages(Site site, ForumThread thread) {
		List<Message> result = new ArrayList<Message>();
		
		try {
        	Document doc;
        	String response;
        	RestClient client;
        	if(site.getDiscussionBoardPortletUrl().equals(""))
        	{
	        	client = RestClient.getInstance(site.getDiscussionBoardUrl());
	            client.Execute(RestClient.RequestMethod.GET);
				response = client.getResponse();
		        doc = Jsoup.parse(response);
		        String portletUrl = doc.select(".portletMainWrap").first().child(0).attr("src");
		        portletUrl = portletUrl.substring(0, portletUrl.lastIndexOf("?"));
		        site.setDiscussionBoardPortletUrl(portletUrl);
        	}
        	
        	client = RestClient.getInstance(site.getDiscussionBoardPortletUrl() + "/discussionForum/message/dfAllMessages");
        	
        	client.AddParam("msgForum", "msgForum");
        	client.AddParam("msgForum:_idcl", thread.getInternalId());
        	client.AddParam("messageId", String.valueOf(thread.getThreadId()));
        	client.AddParam("topicId", String.valueOf(thread.getParent().getId()));
        	client.AddParam("forumId", String.valueOf(thread.getParent().getParent().getId()));
        	
        	client.Execute(RestClient.RequestMethod.POST);
        	response = client.getResponse();
        	doc = Jsoup.parse(response);
        	
        	Elements messagesDOM = doc.select("table[id=msgForum:expandedThreadedMessages] div.hierItemBlock");
        	for (int i = 0; i < messagesDOM.size(); i++) {
        		Element messageElement = messagesDOM.get(i);
        		Element messageTitleLink = messageElement.select("h4.textPanelHeader > div.specialLink > a").first();
        		String tempAuthorString = messageElement.select("h4.textPanelHeader > div.specialLink").text();
        		
        		String tmpParse = messageTitleLink.attr("onclick");
        		tmpParse = tmpParse.substring(tmpParse.indexOf("['messageId'].value='") + 21);
        		tmpParse = tmpParse.substring(0, tmpParse.indexOf("'"));
        		int messageId = Integer.parseInt(tmpParse);
        		
        		tmpParse = messageElement.select("h4.textPanelHeader > div.specialLink > a[title=Responder]").attr("onclick");
        		tmpParse = tmpParse.substring(tmpParse.indexOf("['msgForum:_idcl'].value='") + 26);
        		tmpParse = tmpParse.substring(0, tmpParse.indexOf("'"));
        		String replyInternalId = tmpParse;
        		
        		String name = messageTitleLink.text();
        		String author = tempAuthorString.substring(tempAuthorString.lastIndexOf(" - ") + 3, tempAuthorString.indexOf(" ("));
        		String message = messageElement.select("div.textPanel").text();
        		
        		String strDate = tempAuthorString.substring(tempAuthorString.indexOf(" (") + 2, tempAuthorString.indexOf(") "));
				SimpleDateFormat curFormater = new SimpleDateFormat("MMM dd, yyyy h:mm a"); 
	        	Date modifiedDate = curFormater.parse(strDate); 
        		
        		result.add(new Message(messageId, replyInternalId, name, author, modifiedDate, thread, message));
			}
		} catch (Exception e) {
            e.printStackTrace();
        }
		
		return result;
	}
	
	public void replyMessage(Site site, Message parentMessage, String replyTitle, String replyMessage) {
		try {
        	Document doc;
        	String response;
        	RestClient client;
        	if(site.getDiscussionBoardPortletUrl().equals(""))
        	{
	        	client = RestClient.getInstance(site.getDiscussionBoardUrl());
	            client.Execute(RestClient.RequestMethod.GET);
				response = client.getResponse();
		        doc = Jsoup.parse(response);
		        String portletUrl = doc.select(".portletMainWrap").first().child(0).attr("src");
		        portletUrl = portletUrl.substring(0, portletUrl.lastIndexOf("?"));
		        site.setDiscussionBoardPortletUrl(portletUrl);
        	}
        	
        	client = RestClient.getInstance(site.getDiscussionBoardPortletUrl() + "/discussionForum/message/dfViewThread");
        	client.AddParam("msgForum:select_label", "thread");
        	client.AddParam("msgForum:mainOrForumOrTopic", "dfViewThread");
        	client.AddParam("msgForum", "msgForum");
        	client.AddParam("forumId", String.valueOf(parentMessage.getParent().getParent().getParent().getId()));
        	client.AddParam("msgForum:_idcl", parentMessage.getReplyInternalId());
        	client.AddParam("topicId", String.valueOf(parentMessage.getParent().getParent().getId()));
        	client.AddParam("fromPage", "");
        	client.AddParam("messageId", String.valueOf(parentMessage.getMessageId()));
        	client.Execute(RequestMethod.POST);
        	
        	if (client.getResponseCode() == 200) {
				client = RestClient.getInstance(site.getDiscussionBoardPortletUrl() + "/dfMessageReply");
	        	
	        	client.AddParam("df_compose_title", replyTitle);
	        	client.AddParam("dfCompose:_id16_textarea", replyMessage);
	        	client.AddParam("dfCompose:msgHidden", parentMessage.getMessage());
	        	client.AddParam("dfCompose:titleHidden", parentMessage.getName());
	        	client.AddParam("dfCompose:_id76", "Enviar Mensagem");
	        	client.AddParam("dfCompose", "dfCompose");
	        	
	        	client.Execute(RestClient.RequestMethod.POST);
			}
        	
		} catch (Exception e) {
            e.printStackTrace();
        }
	}
}
